package com.fowo.api.syncAmazon.api;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import com.amazon.spapi.api.FbaOutboundApi;
import com.amazon.spapi.client.ApiException;
import com.amazon.spapi.model.ErrorList;
import com.amazon.spapi.model.fulfillmentoutbound.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.entity.DatainterfaceAuthority;
import com.fowo.api.datainterface.service.DatainterfaceAuthorityService;
import com.fowo.api.entity.*;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.SysCountryMapper;
import com.fowo.api.model.nav.sell.order.NavSellOrderVo;
import com.fowo.api.model.nav.sell.order.detail.NavSellOrderDetailItemVo;
import com.fowo.api.service.NavLogisticsChannelViewService;
import com.fowo.api.service.impl.ListingFatherServiceImpl;
import com.fowo.api.service.impl.ShopInfoServiceImpl;
import com.fowo.api.service.impl.WarehouseServiceImpl;
import com.fowo.api.syncAmazon.util.AmazonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class FbaOutboundApiService {
    @Resource
    private DatainterfaceAuthorityService datainterfaceAuthorityBaseService;
    @Resource
    private AmazonUtil amazonUtil;
    @Resource
    private WarehouseServiceImpl warehouseService;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private SysCountryMapper sysCountryMapper;
    @Resource
    private ListingFatherServiceImpl listingFatherService;
    @Resource
    private NavLogisticsChannelViewService navLogisticsChannelViewService;

    /**
     * 创建物流下单
     * @param navSellOrderVo
     * @return
     * @throws Exception
     */
    public ErrorList createFulfillmentOrder(NavSellOrderVo navSellOrderVo) throws Exception {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);
        Long wid = navSellOrderVo.getDeliveryWarehouse();
        Assert.notNull(wid,"请选择发货仓库");
        Warehouse warehouse = warehouseService.getById(wid);
        Assert.notNull(warehouse,"未找到仓库");
        ShopInfo shopInfo = shopInfoService.getById(warehouse.getSid());
        Assert.notNull(shopInfo,"未找到对应店铺，请重新选择");

        final FbaOutboundApi fbaOutboundApi = amazonUtil.getFbaOutboundApi(entityAuthority, shopInfo);
        CreateFulfillmentOrderRequest body = new CreateFulfillmentOrderRequest();
        body.setMarketplaceId(shopInfo.getMarketplaceId());
        body.setSellerFulfillmentOrderId(navSellOrderVo.getOrderId());//订单号
        body.setDisplayableOrderId(navSellOrderVo.getPlatform().get(0).getPlatformOrderId());//订单号，向买家展示的单号
        body.setDisplayableOrderDate(DateUtil.format(new Date(), DatePattern.UTC_PATTERN));//配送时间


        Long deliveryLogisticsChannel = navSellOrderVo.getDeliveryLogisticsChannel();
        String label = navLogisticsChannelViewService.getLabelById(deliveryLogisticsChannel);
        String shippingMethod = label.substring(label.lastIndexOf("-")+1);
        body.setShippingSpeedCategory(ShippingSpeedCategory.fromValue(shippingMethod));//配送订单的运输方式
//        body.setShippingSpeedCategory(ShippingSpeedCategory.STANDARD);//配送订单的运输方式

//        body.setDeliveryWindow();//预定交货履行订单应交付的时间范围。这只适用于日本市场。
        Address address = new Address();
        address.setName(navSellOrderVo.getDeliveryReceipt());//收件人
        address.setAddressLine1(navSellOrderVo.getDeliveryAddress1());//详细地址
        if(!shopInfo.getRegion().equals("JP")){
            address.setCity(navSellOrderVo.getDeliveryCity());//城市，日本不要
        }
        address.setDistrictOrCounty(navSellOrderVo.getDeliveryArea());//区县
        address.setStateOrRegion(navSellOrderVo.getDeliveryProvince());//州
        address.setPostalCode(navSellOrderVo.getDeliveryZipCode());//邮编
        final SysCountry sysCountry = sysCountryMapper.selectById(navSellOrderVo.getDeliveryCountry());
        address.setCountryCode(sysCountry.getCode());//国家代码
        address.setPhone(navSellOrderVo.getDeliveryPhone());//手机号
        body.setDestinationAddress(address);//配送地址
        body.setFulfillmentAction(FulfillmentAction.SHIP);
        body.setFulfillmentPolicy(FulfillmentPolicy.FILLALL);
//        body.setCodSettings(null);//货到付款设置
//        body.setShipFromCountryCode("");//发货国家编码
//        body.setNotificationEmails(null);//卖家提供的电子邮件地址列表
//        body.setFeatureConstraints(null);//其他设置
        CreateFulfillmentOrderItemList createFulfillmentOrderItemList = new CreateFulfillmentOrderItemList();
        String displayableOrderComment = "";
        for(NavSellOrderDetailItemVo product : navSellOrderVo.getProduct()){
            CreateFulfillmentOrderItem item = new CreateFulfillmentOrderItem();
            final ListingFather listingFather = listingFatherService.getOne(Wrappers.lambdaQuery(ListingFather.class)
                    .eq(ListingFather::getShop, shopInfo.getId())
                    .eq(ListingFather::getPairProduct, product.getProductId()),false);
            Assert.notNull(listingFather,"SKU:"+product.getSku()+"，未配对Listing");
            item.setSellerSku(listingFather.getMsku());//MSKU
            item.setSellerFulfillmentOrderItemId(product.getId().toString());//子表id
            item.setQuantity(product.getQuantity());//数量
//            item.setGiftMessage("");//留言
//            item.setDisplayableComment("");//备注
//            item.setFulfillmentNetworkSku("");//亚马逊的履行网络SKU的项目
//            item.setPerUnitDeclaredValue(null);//产品价格
//            item.setPerUnitPrice(null);//货到付款的价格
//            item.setPerUnitTax(null);//货到付款税
            createFulfillmentOrderItemList.add(item);
            displayableOrderComment += product.getGoodsTitle();
        }
        body.setDisplayableOrderComment(displayableOrderComment.length() > 1000? displayableOrderComment.substring(0,999):displayableOrderComment);//订单备注
        body.setItems(createFulfillmentOrderItemList);
        final CreateFulfillmentOrderResponse fulfillmentOrder = fbaOutboundApi.createFulfillmentOrder(body);
        return fulfillmentOrder.getErrors();
    }

    /**
     * 物流下单测试
     * @throws Exception
     */
    public void createFulfillmentOrderTest() throws Exception {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);
        ShopInfo shopInfo = shopInfoService.getById(1739832830052900865L);

        final FbaOutboundApi fbaOutboundApi = amazonUtil.getFbaOutboundApi(entityAuthority, shopInfo);
        CreateFulfillmentOrderRequest body = new CreateFulfillmentOrderRequest();
        body.setMarketplaceId(shopInfo.getMarketplaceId());
        body.setSellerFulfillmentOrderId("103392714868376576");//订单号
        body.setDisplayableOrderId("GSUNB41570004KG");//订单号，向买家展示的单号
        body.setDisplayableOrderDate("2023-12-28T17:41:13Z");//配送时间
        body.setDisplayableOrderComment("qq");//订单备注
        body.setShippingSpeedCategory(ShippingSpeedCategory.STANDARD);//配送订单的运输方式
//        body.setDeliveryWindow();//预定交货履行订单应交付的时间范围。这只适用于日本市场。
        Address address = new Address();
        address.setName("Antanay Orey");//收件人
        address.setAddressLine1("2273 hidden view st");//详细地址
        if(!shopInfo.getRegion().equals("JP")){
            address.setCity("Carson City");//城市，日本不要
        }
//        address.setDistrictOrCounty(navSellOrderVo.getDeliveryArea());//区县
        address.setStateOrRegion("NV");//州
        address.setPostalCode("89156");//邮编
//        final SysCountry sysCountry = sysCountryMapper.selectById(navSellOrderVo.getDeliveryCountry());
        address.setCountryCode("US");//国家代码
        address.setPhone("7029697516");//手机号
        body.setDestinationAddress(address);//配送地址
        body.setFulfillmentAction(FulfillmentAction.SHIP);
        body.setFulfillmentPolicy(FulfillmentPolicy.FILLALL);
//        body.setCodSettings(null);//货到付款设置
//        body.setShipFromCountryCode("US");//发货国家编码
//        body.setNotificationEmails(null);//卖家提供的电子邮件地址列表
//        body.setFeatureConstraints(null);//其他设置
        CreateFulfillmentOrderItemList createFulfillmentOrderItemList = new CreateFulfillmentOrderItemList();
        CreateFulfillmentOrderItem item = new CreateFulfillmentOrderItem();
        item.setSellerSku("1B-BG0054-A");//MSKU
        item.setSellerFulfillmentOrderItemId("1701959138808532998");//子表id
        item.setQuantity(1);//数量
//        item.setGiftMessage("1112");//留言
//        item.setDisplayableComment("aassd");//备注
//        item.setFulfillmentNetworkSku(null);//亚马逊的履行网络SKU的项目
//        item.setPerUnitDeclaredValue(null);//产品价格
//        item.setPerUnitPrice(null);//货到付款的价格
//        item.setPerUnitTax(null);//货到付款税
        createFulfillmentOrderItemList.add(item);
        body.setItems(createFulfillmentOrderItemList);
        CreateFulfillmentOrderResponse response = fbaOutboundApi.createFulfillmentOrder(body);
        System.out.println(response);
    }

    /**
     * 获取配送信息
     * @param shopId
     * @param orderId
     * @return
     * @throws ApiException
     */
    public String getFulfillmentOrder(Long shopId,String orderId){
        String trackingNumber = null;
        try{
            DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);
            ShopInfo shopInfo = shopInfoService.getById(shopId);

            FbaOutboundApi fbaOutboundApi = amazonUtil.getFbaOutboundApi(entityAuthority, shopInfo);
            GetFulfillmentOrderResponse response = fbaOutboundApi.getFulfillmentOrder(orderId);
            GetFulfillmentOrderResult result = response.getPayload();
            FulfillmentShipmentList fulfillmentShipments = result.getFulfillmentShipments();

            if(null != fulfillmentShipments){
                for(FulfillmentShipment fulfillmentShipment : fulfillmentShipments){
                    FulfillmentShipmentPackageList fulfillmentShipmentPackages = fulfillmentShipment.getFulfillmentShipmentPackage();
                    if(null != fulfillmentShipmentPackages){
                        trackingNumber = fulfillmentShipmentPackages.stream()
                                .map(p -> p.getTrackingNumber())
                                .collect(Collectors.joining(","));
                    }
                }
            }
        }catch (Exception e){
            log.error("更新订单："+orderId+" 跟踪号异常",e);
        }
        return trackingNumber;
    }

    /**
     * 取消物流下单
     * @param orderId
     * @param deliveryWarehouse
     * @throws ApiException
     */
    public void cancelFulfillmentOrder(String orderId,Long deliveryWarehouse) throws ApiException {
        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Amazon"), false);
        Warehouse warehouse = warehouseService.getById(deliveryWarehouse);
        Assert.notNull(warehouse,"未找到仓库");
        ShopInfo shopInfo = shopInfoService.getById(warehouse.getSid());
        Assert.notNull(shopInfo,"未找到对应店铺，请重新选择");

        final FbaOutboundApi fbaOutboundApi = amazonUtil.getFbaOutboundApi(entityAuthority, shopInfo);
        CancelFulfillmentOrderResponse response = fbaOutboundApi.cancelFulfillmentOrder(orderId);

        Assert.isNull(response.getErrors(),"取消物流下单异常");
    }
}
